<?php

namespace backend\modules\languages\models\form;

use Yii;
use yii\base\Model;
use yii\helpers\FileHelper;
use yii\data\ArrayDataProvider;
use backend\models\Clients;

/**
 * Description of Filter
 *
 * @author loong
 */
class Filter extends Model
{
    public $language;
    public $client;
    public $search;
    public $limit = 20;
    public $key;

    public function init()
    {
        if (!Yii::$app->request->isPost){
            $this->load(Yii::$app->session->get('mod_langs.items'));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['language', 'client'], 'safe'],
            [['search'], 'string', 'max' => '50'],
            [['limit'], 'integer']
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'language' => Yii::t('mod_langs', 'LANGUAGE'),
            'client' => Yii::t('mod_langs', 'CLIENT'),
            'search' => Yii::t('mod_langs', 'SEARCH'),
            'limit' => Yii::t('mod_langs', 'LIMIT'),
            'category' => Yii::t('mod_langs', 'CATEGORY'),
            'key' => Yii::t('mod_langs', 'OVERRIDE_FIELD_KEY'),
            'value' => Yii::t('mod_langs', 'OVERRIDE_FIELD_VALUE')
        ];
    }

    /**
     * 搜索结果
     * @param array $params 搜索参数
     * @return ArrayDataProvider
     */
    public function search($params)
    {
        $this->load($params);
        if (Yii::$app->request->isPost){
            unset($params[Yii::$app->request->csrfParam]);
            Yii::$app->session->set('mod_langs.items', $params);
        }
        $cache = Yii::$app->cache;
        if (!$cache->exists('overrides')) {
            $clients = Clients::find()->where(['status' => 1])->orderBy('ordering')->all();
            $overrideFiles = [];
            foreach ($clients as $client) {
                $path = Yii::getAlias('@' . $client->name) . '/messages/overrides/';
                $files = FileHelper::findFiles($path, ['only' => ['*.override.php']]);
                foreach ($files as $file) {
                    $fileInfo = explode('.', substr($file, strlen($path)));
                    $messages = include_once $file;
                    foreach ($messages as $key => $value) {
                        $overrideFiles[] = [
                            'id' => md5($client->name . $fileInfo[0] . $fileInfo[1] . $key),
                            'client' => ucfirst($client->name),
                            'language' => $fileInfo[0],
                            'category' => $fileInfo[1],
                            'key' => $key,
                            'value' => $value
                        ];
                    }
                }
            }
            $cache->set('overrides', $overrideFiles);
        }

        $overrideFiles = $cache->get('overrides');

        if ($this->language) {
            $newOverrideFiles = [];
            foreach ($overrideFiles as $item) {
                if ($item['language'] == $this->language) {
                    $newOverrideFiles[] = $item;
                }
            }
            $overrideFiles = $newOverrideFiles;
        }

        if ($this->client) {
            $clientName = Clients::findOne($this->client)->name;
            $newOverrideFiles = [];
            foreach ($overrideFiles as $item) {
                if ($item['client'] == ucfirst($clientName)) {
                    $newOverrideFiles[] = $item;
                }
            }
            $overrideFiles = $newOverrideFiles;
        }

        if ($this->search) {
            $newOverrideFiles = [];
            foreach ($overrideFiles as $item) {
                $inKey = substr_count(strtolower($item['key']), strtolower($this->search)) > 0;
                $inVlue = substr_count(strtolower($item['value']), strtolower($this->search)) > 0;
                if ($inKey || $inVlue) {
                    $newOverrideFiles[] = $item;
                }
            }
            $overrideFiles = $newOverrideFiles;
        }

        $dataProvider = new ArrayDataProvider([
            'allModels' => $overrideFiles,
            'modelClass' => static::class,
            'pagination' => [
                'pageSize' => $this->limit
            ],
            'sort' => [
                'attributes' => ['key', 'client', 'language', 'category', 'value']
            ]
        ]);

        return $dataProvider;
    }

    /**
     * 获取覆盖语言的ID
     * @param string $client 应用名称
     * @param string $category 语言类
     * @param string $key 文本常量
     * @param string $language 语言代码
     * @return string
     */
    public static function getId($client, $category, $key, $language = null)
    {
        $language = $language ?? Yii::$app->language;
        return md5($client . $language . $category . $key);
    }
}
